package cookie;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/10/10 8:37
 * @Description: 校验cookie
 */
@WebServlet(name = "auto", urlPatterns = {"/auto"})
public class AutoServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {

    String username = getValue(request.getCookies(), "username");
    String password = getValue(request.getCookies(), "password");

    // key=value
    request.setAttribute("username", username);
    request.setAttribute("password", password);

    request.getRequestDispatcher("/check")
        .forward(request, response);
  }

  public String getValue(Cookie[] cks, String name) {
    if (cks == null) {
      return null;
    }

    for (Cookie ck : cks) {
      if (ck.getName().equals(name)) {
        return ck.getValue();
      }
    }

    return null;
  }
}
